package com.lemon.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lemon.mapper.GoodMapper;
import com.lemon.pojo.Goods;

import com.lemon.util.RedisConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lemon
 * @version V1.0
 * @date 2020/10/23
 */
@RestController
@RequestMapping("/good")
public class GoodController {
    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GoodMapper goodMapper;
    @RequestMapping("/show")
    public String show() throws JsonProcessingException {
        //判断redis中是否有数据
        String str = (String) redisTemplate.opsForValue().get(RedisConf.GOODS);
        if (str != null){
            String string = objectMapper.writeValueAsString(str);
            return string;
        }
        //如果没有数据就查询数据库并且存入redis
        List<Goods> all = goodMapper.findAll();
        System.out.println(all);
        String string = objectMapper.writeValueAsString(all);
        //将查询数据存入redis
        redisTemplate.opsForValue().set(RedisConf.GOODS,string);
        return string;
    }

    @RequestMapping("/insert")
    public String insert(Goods goods) throws JsonProcessingException {
        String str = (String) redisTemplate.opsForValue().get(RedisConf.GOODS);
        List<Goods> goods1 = objectMapper.readValue(str, new TypeReference<List<Goods>>() {});
        goods1.add(goods);
        //将数据封装回redis中
        String string = objectMapper.writeValueAsString(goods1);
        //将查询数据存入redis
        redisTemplate.opsForValue().set(RedisConf.GOODS,string);
        //将数据再取出返回到页面
        String str1 = (String) redisTemplate.opsForValue().get(RedisConf.GOODS);
        return str1;
    }
}
